package com.brand.data.service.yqdz;

import java.net.SocketTimeoutException;
import java.util.Map;

import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.brand.data.model.MonitorException;
import com.brand.data.model.RequestParam;
import com.brand.data.service.AbstractBaseService;
import com.brand.data.service.DataCrawlService;
import com.brand.data.service.LoginService;
import com.brand.data.util.CookieUtil;
import com.brand.data.util.CookieUtil.Cookie;

/**
 * @author scl
 * @date 2018年4月11日 下午2:46:55
 * @version 1.0
 * @description 一汽大众
 */
@Service
public class YqdzCrawService extends AbstractBaseService implements DataCrawlService {
	private static final String BRAND_NAME = "YI_QI_DA_ZHONG";
	private static final String URL_LIST = "https://portal.faw-vw.com/asjct/SAPAfterSales/vrhsearch.do";
	private static final String URL_DETAIL = "https://portal.faw-vw.com/asjct/SAPAfterSales/SubInfoSearch.do";
	@Autowired
	@Qualifier("yqdzLoginService")
	private LoginService loginService = new YqdzLoginService();
	private RequestParam getParams(String vin) {
		return RequestParam.newParam().addParam("actions","clwxdacx")
					.addParam("actiontype","")
					.addParam("url1","http://10.228.4.136:9081/SAPAfterSales/pages/clxxcx/clwxdacx_input.jsp")
					.addParam("brandPrefix","au_")
					.addParam("dealercode1","")
					.addParam("ip1","10.226.17.3")
					.addParam("queryString1","point=clwxdacx&sourse=portal1")
					.addParam("remoteHost1","10.226.17.3")
					.addParam("remotePort1","webs3-webseald-l79por316")
					.addParam("remoteUser1","")
					.addParam("method1","GET")
					.addParam("pathInfo1","")
					.addParam("localAddr1","10.226.21.132")
					.addParam("localName1","sapaftersaleswswas01")
					.addParam("sourse","portal1")
					.addParam("settledate","")
					.addParam("settledate2","")
					.addParam("orderdate","")
					.addParam("orderdate2","")
					.addParam("fpdate","")
					.addParam("fpdate2","")
					.addParam("sxdate","")
					.addParam("sxdate2","")
					.addParam("proxysort","-1")
					.addParam("vincode", vin)
					.addParam("vehiclecode","")
					.addParam("xslc","")
					.addParam("gzms","");
	}
	public Object search(String vin) {
		return null;
	}
	public Object queryList(String vin) {
		return doQuery(URL_LIST, getParams(vin),0);
	}
	public Object queryDetail(RequestParam param) {
		return doQuery(URL_DETAIL,param,0);
	}
	private synchronized Cookie validLogin() {
		Cookie cookie = CookieUtil.getCookie(BRAND_NAME);
		if (cookie == null){
			loginService.login();
			cookie = CookieUtil.getCookie(BRAND_NAME);
		}
		return cookie;
	}

	private String doQuery(String url, RequestParam params,int times) {
		Cookie cookie = null;
		try {
			cookie = validLogin();
			Map<String, String> cookies = cookie.getCookie();
			if (URL_LIST.equals(url)){
                params.addParam("userlogincode", CookieUtil.getCookies(BRAND_NAME).get("username"));
            }
			//开始请求
            Response response = getConnection(url, params, RequestHeader.initHeader(), cookies)
                    .timeout(30 * 1000)
					.method(Method.POST).execute();
            String body = response.body();
            if (body.contains("请先输入用户名")||body.contains("数据被拦截")){
                throw new RuntimeException("账号有问题了，请更换账号");
            }
            if (body.contains("500: java.lang.NullPointerException")) {
            	throw new RuntimeException("页面渲染失败");
			}
            CookieUtil.addCookies(BRAND_NAME,response.cookies());
            return body.replaceAll("&nbsp;","");
		} catch (Exception e) {
			try {
			    if ( !(e instanceof SocketTimeoutException)){
                    CookieUtil.clearCookie(BRAND_NAME,cookie.getVersion());
                }
			} catch (Exception e1) {}
			if (times > 3) {
				if (e instanceof MonitorException){
					throw (MonitorException) e;
				}
				throw new MonitorException("查询失败",e);
			}
			try {
				if (e.getMessage().contains("页面渲染失败")) {
					Thread.sleep(30*1000);
				}
			} catch (Exception e1) {}
			return doQuery(url, params, ++times);
		}
	}
}
